package com.bluesky.plum.uimodels.render.html;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bluesky.javawebbrowser.domain.html.HtmlPage;
import com.bluesky.javawebbrowser.domain.html.tags.Tag;
import com.bluesky.plum.uimodels.standard.StandardUIComponentType;

public class TemplateUtil {
	public static String FILE_NAME = "com/bluesky/plum/uimodels/render/html/template.html";
	private static Map<String, Tag> templateTags;

	static private String getContents() {
		// ...checks on aFile are elided
		StringBuilder contents = new StringBuilder();

		try {
			// use buffering, reading one line at a time
			// FileReader always assumes default encoding is OK!
			InputStream is = TemplateUtil.class.getClassLoader()
					.getResourceAsStream(FILE_NAME);
			Reader reader = new InputStreamReader(is);

			BufferedReader input = new BufferedReader(reader);
			try {
				String line = null; // not declared within while loop
				/*
				 * readLine is a bit quirky : it returns the content of a line
				 * MINUS the newline. it returns null only for the END of the
				 * stream. it returns an empty String if two newlines appear in
				 * a row.
				 */
				while ((line = input.readLine()) != null) {
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			} finally {
				input.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		return contents.toString();
	}

	private static void loadFromFile() {

		String html = getContents();

		templateTags = new HashMap<String, Tag>();
		HtmlPage page = new HtmlPage(html);

		List<String> list = new ArrayList<String>();
		for (StandardUIComponentType t : StandardUIComponentType.values()) {
			list.add(t.toString());
		}

		String[] ids = list.toArray(new String[] {});

		for (String id : ids) {
			Tag tag = page.getRoot().getById(id);
			if (tag != null)
				templateTags.put(id, tag);
		}

	}

	public static Tag getTag(String name) {
		if (templateTags == null)
			loadFromFile();

		return templateTags.get(name);
	}

	public static void main(String[] args) {
		Tag tag = TemplateUtil.getTag("TextBox");
		System.out.println(tag.toHtml());

		tag = TemplateUtil.getTag("Button");
		System.out.println(tag.toHtml());

		// parse html segment
		HtmlPage hp = new HtmlPage(tag.toHtml());
		Tag tag2 = hp.getRoot().getById("Button");
		System.out.println(tag2.toHtml());
	}
}
